package com.file.manage;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements AdapterView.OnItemClickListener, View.OnClickListener {

    private Context context;
    private ListView fileListView;
    private Button btnDelete, btnSelectAll;
    private FileListAdapter adapter;
    private static int DEFAULT_SORT = FileManager.SORT_TIME;
    private View bottomMenu;
    private boolean showCheck = false;//是否显示点击按钮
    private boolean checked = false;//checked点击状态
    private boolean checkListItem = false;//判断item是否点击的标记
    private List<CheckEntity> dataList;
    private static String filePath = Environment.getExternalStorageDirectory().getPath()
            + "/FileManage/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        fileListView = (ListView) this.findViewById(R.id.listview1);
        bottomMenu = (View) this.findViewById(R.id.bottomMenu);
        btnDelete = (Button) this.findViewById(R.id.btnDelete);
        btnSelectAll = (Button) this.findViewById(R.id.btnSelectAll);
        dataList = new ArrayList<>();
        adapter = new FileListAdapter(this, dataList, showCheck);
        fileListView.setAdapter(adapter);
        fileListView.setOnItemClickListener(this);
        btnDelete.setOnClickListener(this);
        btnSelectAll.setOnClickListener(this);
        fileTask(DEFAULT_SORT, checked);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, R.id.setUp, Menu.NONE, "创建文件")
                .setIcon(R.drawable.ic_add)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        menu.add(Menu.NONE, R.id.delete, Menu.NONE, R.string.delete)
                .setIcon(R.drawable.delete)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        SubMenu sub = menu.addSubMenu("排序").setIcon(R.drawable.icon_sort);
        sub.add(0, R.id.sort_alpha, 0, R.string.sort_alpha);
        sub.add(0, R.id.sort_size, 0, R.string.sort_size);
        sub.add(0, R.id.sort_time, 0, R.string.sort_time);
        sub.add(0, R.id.sort_type, 0, R.string.sort_type);
        sub.getItem().setShowAsAction(
                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
            case R.id.delete:
                if (showCheck) {
                    showCheck = false;
                    bottomMenu.setVisibility(View.GONE);
                    fileTask(DEFAULT_SORT, checked);
                } else {
                    showCheck = true;
                    bottomMenu.setVisibility(View.VISIBLE);
                    fileTask(DEFAULT_SORT, checked);
                }
                break;
            case R.id.sort_alpha:
                DEFAULT_SORT = FileManager.SORT_ALPHA;
                fileTask(DEFAULT_SORT, checked);
                break;
            case R.id.sort_size:
                DEFAULT_SORT = FileManager.SORT_SIZE;
                fileTask(DEFAULT_SORT, checked);
                break;
            case R.id.sort_time:
                DEFAULT_SORT = FileManager.SORT_TIME;
                fileTask(DEFAULT_SORT, checked);
                break;
            case R.id.sort_type:
                DEFAULT_SORT = FileManager.SORT_TYPE;
                fileTask(DEFAULT_SORT, checked);
                break;
            case R.id.setUp:
                try {
                    CreateText();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    private void fileTask(int sort, boolean check) {
        FileManager fileManager = new FileManager();
        fileManager.setSortType(sort);
        dataList.clear();
        List<String> fileList = fileManager.getNextDir(filePath, true);
        if (fileList != null && fileList.size() > 0 && !fileList.get(0).equals("Empty")) {
            CheckEntity checkEntity;
            for (String string : fileList) {
                checkEntity = new CheckEntity();
                checkEntity.setFileName(string);
                checkEntity.setFileSize(fileManager.caculateFileSize(filePath + string));
                checkEntity.setFileImage(FileUtil.getFileTypeDrawable(FileUtil.getFileSuffix(string), context));
                checkEntity.setDate(fileManager.getFileModifyTime(filePath + string));
                checkEntity.setSelectCheck(check);
                dataList.add(checkEntity);
            }
            fileListView.requestLayout();
            adapter.setmList(dataList, showCheck);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        // TODO Auto-generated method stub
        if (showCheck) {
            // 判断是否点击的是已被选中的item
            if (dataList.get(position).getSelectCheck()) {
                checkListItem = false;
            } else {
                checkListItem = true;
            }
            dataList.get(position).setSelectCheck(checkListItem);
            fileListView.requestLayout();
            adapter.setmList(dataList, showCheck);
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            String fileName = dataList.get(position).getFileName().toString();
            Uri uri = Uri.parse("file://" + filePath + fileName);
            intent.setDataAndType(uri, FileUtil.getMIMEType(fileName));
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "没有可用打开文件的应用", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btnDelete:
                FileManager fileManager = new FileManager();
                for (int i = 0; i < dataList.size(); i++) {
                    if (dataList.get(i).getSelectCheck()) {
                        String path = filePath + dataList.get(i).getFileName().toString();
                        fileManager.deleteTarget(path);
                    }
                }
                fileListView.requestLayout();
                fileTask(DEFAULT_SORT, false);
                break;
            case R.id.btnSelectAll:
                if (checked) {
                    checked = false;
                    btnSelectAll.setText("全选");
                    fileTask(DEFAULT_SORT, checked);
                } else {
                    checked = true;
                    btnSelectAll.setText("撤销");
                    fileTask(DEFAULT_SORT, checked);
                }
                break;
            default:
                break;
        }

    }

    //创建文件夹及文件
    public void CreateText() throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                //按照指定的路径创建文件夹
                file.mkdirs();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        String txt = filePath + "txt" + ".txt";
        String jpg = filePath + "jpg" + ".jpg";
        String apk = filePath + "apk" + ".apk";
        String doc = filePath + "doc" + ".doc";
        String mp4 = filePath + "mp4" + ".mp4";

        File dirTxt = new File(txt);
        File dirJpg = new File(jpg);
        File dirApk = new File(apk);
        File dirDoc = new File(doc);
        File dirMp4 = new File(mp4);

        if (!dirTxt.exists()) {
            try {
                //在指定的文件夹中创建文件
                dirTxt.createNewFile();
                dirJpg.createNewFile();
                dirApk.createNewFile();
                dirDoc.createNewFile();
                dirMp4.createNewFile();
                fileTask(DEFAULT_SORT, false);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

    }

}
